<template>
  <div class="app-container calendar-list-container" v-loading="allLoading">

    <div class="apply-query">

      <el-row class="filter-query" >
        <el-col><i class="el-icon-search"/>&nbsp;&nbsp;筛选查询</el-col>
      </el-row><br>

      <el-form :inline="true" :model="listQuery"  >
        <el-row>
          <el-col :span="24" style="margin-left: 3%">
            <el-form-item label="项目名称" >
              <el-input v-model="listQuery.name"  class="filter-item" placeholder="项目名称"  @keyup.enter.native="handleFilter" ></el-input>
            </el-form-item>

            <el-form-item label="编码">
              <el-input v-model="listQuery.code"  class="filter-item" placeholder="编码"  @keyup.enter.native="handleFilter" ></el-input>
            </el-form-item>

            <el-form-item label="年份">
              <el-input v-model="listQuery.year"  class="filter-item" placeholder="年份"  @keyup.enter.native="handleFilter"></el-input>
            </el-form-item>


            <el-button class="filter-item" type="primary" icon="search" @click="handleFilter" style="margin-left: 3%">搜索</el-button>
            <el-button type="primary"  @click="reset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <!--列表-->
    <div class="data-list">
      <el-row class="list-content">
        <el-col :span="1" style="text-align: center"><svg-icon icon-class="chart"/></el-col>
        <el-col :span="2">数据列表</el-col>
        <el-col :span="20" style="text-align: right;margin-right: 3%">
          <el-button class="filter-item" v-if="tenantManager_btn_add" style="margin-left: 10px;" @click="handleCreate" type="primary"
                     icon="edit">添加</el-button>
        </el-col>
      </el-row>
    <el-table :key='tableKey' :data="list" v-loading.body="listLoading" border fit highlight-current-row >
      <el-table-column  align="center" label="年份">
        <template slot-scope="scope">
          <span>{{scope.row.year}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="编码">
        <template slot-scope="scope">
          <span>{{scope.row.code}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="项目名称">
        <template slot-scope="scope">
          <span>{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{scope.row.createTime| cutTime}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="项目到期时间">
        <template slot-scope="scope">
          <span>{{scope.row.expirationTime| cutTime}}</span>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="是否开放注册" prop="isRegister" :formatter="formatter.formatRegister">
      </el-table-column>
      <el-table-column align="center" label="操作" width="400">
        <template slot-scope="scope">
          <el-button v-if="tenantManager_btn_edit" size="small" type="success" @click="handleUpdate(scope.row)">编辑
          </el-button>
          <el-button v-if="tenantManager_btn_del" size="small" type="warning" @click="deleteStandard(scope.row)">删除标准库
          </el-button>
          <el-button v-if="tenantManager_btn_del" size="small" type="danger" @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div v-show="!listLoading" class="pagination-container">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
        :page-sizes="[10, 20, 30, 50, 100, 200]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px"  v-loading="loading">
        <el-form-item label="编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入编码"></el-input>
        </el-form-item>
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称" onkeypress="javascript:if(event.keyCode == 32)event.returnValue = false"></el-input>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input v-model="form.year" placeholder="请输入项目年份"></el-input>
        </el-form-item>
        <el-form-item label="管理员账号" prop="account" v-if="dialogStatus !== 'update'">
          <el-input v-model="form.account" placeholder="请输入项目管理员账号" :disabled="dialogStatus === 'update'"></el-input>
        </el-form-item>
        <el-form-item label="管理员密码" prop="password"  v-if="dialogStatus !== 'update'">
          <el-input v-model="form.password" placeholder="请输入项目管理员密码"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item class="form-item" label="项目标准库" >
          <template>
            <el-select v-model="form.selectTenant" placeholder="请选择项目标准库">
              <el-option v-for="item in items" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="到期时间" prop="expirationTime">
          <el-date-picker v-model="form.expirationTime" type="datetime" placeholder="请选择到期时间"></el-date-picker>
        </el-form-item>
        <el-form-item label="开放注册" prop="isRegister">
          <el-radio-group v-model="form.isRegister">
            <el-radio class="radio" :label="1">开放</el-radio>
            <el-radio class="radio" :label="0">不开放</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="form-item" label="添加项目图片">
          <el-upload ref="picture"
            action="api/oss/upload"
            :headers="uploadHeaders"
            list-type="picture-card"
            :file-list="appearanceImageList"
            :on-success="handleUploadSuccess('appearance')"
            :on-remove="handleRemove('appearance')"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel('form')">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create('form')" :disabled="flag">确 定</el-button>
        <el-button v-else type="primary" @click="update('form')">确 定</el-button>
      </div>
    </el-dialog>
     <el-dialog title="授予用户" :visible.sync="dialogUserVisible" center width="350px">
       <el-select v-model="currentUser"     filterable
          remote
          reserve-keyword
          placeholder="请输入关键词"
          :remote-method="remoteMethod"
          :loading="loading">
          <el-option v-for="item in users" :key="item.id" :label="item.name" :value="item.id">
            <span>{{item.name}}</span>
          </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelUser()">取 消</el-button>
        <el-button type="primary" @click="confirmUser()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { phoneValidate } from '@/api/admin/business';
import {
  page,
  addObj,
  getObj,
  delObj,
  putObj,
  updateUser,
  getOwner,
  standardLibrary,
  queryUserTenant,
  deleteStandardLibrary
} from '@/api/admin/tenant/index';
import { mapGetters } from 'vuex';
import formatter from '@/utils/formatter'
import { getToken } from '@/utils/auth'
export default {
  name: 'tenant',
  data() {
    const yearValidate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入年份'))
      } else if (!/^[0-9]*$/.test(value)) {
        callback(new Error('请输入合理数字'))
      } else {
        callback()
      }
    }
    const usernameValidation = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入管理员账号'));
      } else {
        phoneValidate(value).then(response => {
          if (response.data) {
            callback(new Error('管理员账号已存在'))
          } else {
            callback()
          }
        })
      }
    }
    return {
      allLoading: false,
      loading: false,
      formatter,
      uploadHeaders: {
        Authorization: null
      },
      appearanceImageList: [],
      items: [],
      form: {
        code: undefined,
        name: undefined,
        description: undefined,
        account: undefined,
        isSuperTenant: '0',
        isRegister: 1,
        picture: '',
        selectTenant: undefined
      },
      rules: {
        account: [{
          required: true,
          validator: usernameValidation,
          trigger: 'blur'
        }],
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 20,
            message: '长度在 2 到 20 个字符',
            trigger: 'blur'
          }
        ],
        expirationTime: [
          {
            required: true,
            message: '请选择到期时间',
            trigger: 'blur'
          }
        ], name: [
          {
            required: true,
            message: '请输入最后更新时间',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入管理员密码',
            trigger: 'blur'
          },
          {
            min: 5,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        year: [
          {
            required: true,
            validator: yearValidate,
            trigger: 'blur'
          }, {
            min: 2,
            max: 10,
            message: '限制2-10个字符',
            trigger: 'blur'
          }
        ]
      },
      list: null,
      users: [],
      total: null,
      listLoading: true,
      flag: false,
      currentId: undefined,
      currentUser: undefined,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        code: undefined,
        year: undefined,
        description: undefined
      },
      dialogFormVisible: false,
      dialogUserVisible: false,
      dialogStatus: '',
      tenantManager_btn_edit: false,
      tenantManager_btn_del: false,
      tenantManager_btn_add: false,
      tenantManager_btn_user: false,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      tableKey: 0
    }
  },
  created() {
    this.getQuery()
    this.getList();
    this.uploadHeaders.Authorization = getToken()
    this.tenantManager_btn_edit = this.elements['tenantManager:btn_edit'];
    this.tenantManager_btn_del = this.elements['tenantManager:btn_del'];
    this.tenantManager_btn_add = this.elements['tenantManager:btn_add'];
    this.tenantManager_btn_user = this.elements['tenantManager:btn_user'];
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    getQuery() {
      const tenantQuery = window.sessionStorage.getItem('tenantQuery')
      if (tenantQuery) {
        this.listQuery = JSON.parse(tenantQuery)
      }
    },
    getList() {
      this.listLoading = true;
      page(this.listQuery)
        .then(response => {
          this.list = response.data.rows;
          this.total = response.data.total;
          this.listLoading = false;
        })
    },
    getTenant() {
      queryUserTenant().then(res => {
        this.items = res.data
      })
    },
    handleFilter() {
      this.getList();
    },
    reset() {
      this.listQuery = {}
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleCreate() {
      this.getTenant()

      this.resetTemp();
      this.dialogStatus = 'create';
      this.form.isRegister = 1;
      this.dialogFormVisible = true;
      this.appearanceImageList = [];
    },
    handleUpdate(row) {
      this.getTenant()
      this.allLoading = true
      getObj(row.id)
        .then(response => {
          this.appearanceImageList = [];
          this.form = response.data;
          response.data.account = response.data.owner
          if (response.data.picture != null) {
            const imgs = response.data.picture.split(',');
            if (imgs.length > 0 && imgs !== '') {
              for (let i = 0; i < imgs.length; i++) {
                this.appearanceImageList.push({ name: 'a' + i, url: imgs[i] })
              }
            }
          } else {
            this.form.picture = '';
          }
          this.dialogFormVisible = true;
          this.dialogStatus = 'update';
          this.allLoading = false
        });
    },
    handlerUser(row) {
      this.dialogUserVisible = true;
      this.currentId = row.id;
      getOwner(row.id).then(response => {
        const user = response.data;
        this.users.push(user);
        this.currentUser = row.owner
      });
    },
    cancelUser() {
      this.dialogUserVisible = false;
    },
    confirmUser() {
      updateUser(this.currentId, { userId: this.currentUser }).then(() => {
        this.$notify({
          title: '成功',
          message: '授予成功',
          type: 'success',
          duration: 2000
        });
        this.dialogUserVisible = false;
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        page({ name: query, username: query }).then(response => {
          this.loading = false;
          this.users = response.data.rows
        });
      } else {
        this.users = [];
      }
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delObj(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
              const index = this.list.indexOf(row);
              this.list.splice(index, 1);
            });
        });
    },
    deleteStandard(row) {
      console.log('删除标准库', row);
      // 删除标准库
      this.$confirm('此操作将永久删除该项目的标准库, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteStandardLibrary(row.id)
            .then(() => {
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              });
            });
        });
    },
    create(formName) {
      const set = this.$refs;

      set[formName].validate(valid => {
        if (valid) {
          this.form.expirationTime = this.form.expirationTime.getTime()
          this.loading = true;
          this.flag = true;
          addObj(this.form)
            .then(() => {
              this.dialogFormVisible = false;
              this.getList();
              this.loading = false;
              this.flag = false;
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              });
            })
        } else {
          return false;
        }
      });
    },
    cancel(formName) {
      this.dialogFormVisible = false;
      // this.$refs.resetFields()
      const set = this.$refs;
      set[formName].resetFields();
    },
    update(formName) {
      // 判断该项目下是否已有标准库
      this.allLoading = true
      if (this.form.selectTenant) {
        standardLibrary(this.form.tenantId).then(res => {
          if (!res.data) {
            this.allLoading = false
            this.$notify({
              title: '失败',
              message: '该项目已存在标准库，同步失败',
              type: 'error',
              duration: 2000
            });
          } else {
            this.updateTenant(formName)
          }
        });
      } else {
        this.updateTenant(formName)
      }
    },
    updateTenant(formName) {
      const set = this.$refs;

      const numReg = /^[0-9]+$/
      const numRe = new RegExp(numReg)
      if (!numRe.test(this.form.expirationTime) && this.form.expirationTime != null) {
        this.form.expirationTime = this.form.expirationTime.getTime()
      }
      set[formName].validate(valid => {
        if (valid) {
          this.dialogFormVisible = false;
          this.form.password = undefined;
          putObj(this.form.id, this.form).then(() => {
            this.allLoading = false
            this.dialogFormVisible = false;
            this.getList();
            this.$notify({
              title: '成功',
              message: '编辑成功',
              type: 'success',
              duration: 2000
            });
          });
        } else {
          return false;
        }
      });
    },
    handleUploadSuccess() {
      // 这里才是真正的钩子
      return (response, file, fileList) => {
        const list = []
        for (const f of fileList) {
          if (f.response) {
            list.push(f.response.data)
          } else {
            list.push(f.url)
          }
        }
        this.form.picture = list.toString();
      }
    },
    // 上传图片
    handleRemove() {
      return (file, fileList) => {
        const list = []
        for (const f of fileList) {
          if (f.response) {
            list.push(f.response.data)
          } else {
            list.push(f.url)
          }
        }
        this.form.picture = list.toString();
      }
    },
    resetTemp() {
      this.form = {
        code: undefined,
        name: undefined,
        description: undefined,
        isSuperTenant: '0'
      };
    }
  },
  beforeDestroy() {
    window.sessionStorage.setItem('tenantQuery', JSON.stringify(this.listQuery))
  }
}
</script>
